package com.cloud_disk.service.impl;

import com.cloud_disk.mapper.LinkInfoMapper;
import com.cloud_disk.service.LinkInfoService;
import com.cloud_disk.vo.ShareFileLinkInfo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;
/**
 * @author 徐华星
 * 日期 2021/12/21
 */
@Service
public class LinkInfoServiceImpl implements LinkInfoService {

    @Autowired
    private LinkInfoMapper linkInfoMapper;

    @Override
    public ShareFileLinkInfo getLinkInfoByURL(String url) {
        return linkInfoMapper.getLinkInfoByURL(url);
    }

    @Override
    public ShareFileLinkInfo getLinkInfoById(Integer id) {
        return linkInfoMapper.getLinkInfoById(id);
    }

    /**
     * 创建链接
     * @param haspassword 是否有密码
     * @param lifetime 生存时间(天)
     * @param userid 用户id
     * @param fileid 文件id
     * @return
     */
    @Override
    public String createLink(Integer haspassword,Integer lifetime,Integer userid,Integer fileid) {

        Random random = new Random(new Date().getTime());
        int id =random.nextInt();
        String url = RandomStringUtils.randomAlphanumeric(10);
        String password = RandomStringUtils.randomAlphanumeric(4 * haspassword);
        ShareFileLinkInfo info = new ShareFileLinkInfo();

        info.setId(id);
        info.setUrl(url);
        info.setPassword(password);
        info.setStarttime(new Date());
        info.setLivetime(new Date((new Date()).getTime()+lifetime*24*1000*3600l));
        info.setUserid(userid);
        info.setFileid(fileid);

        linkInfoMapper.addShareLink(info);

        return url;
    }

    @Override
    public List<ShareFileLinkInfo> getAllShareLinkByUserId(Integer userid) {
        return linkInfoMapper.getAllShareLinkByUserId(userid);
    }

    @Override
    public void modifyLinkInfoLivetimeByID(Integer id, Integer lifetime) {
        ShareFileLinkInfo info = linkInfoMapper.getLinkInfoById(id);
        linkInfoMapper.updateLinkInfoLivetimeByInfoid(id,new Date(), new Date(info.getStarttime().getTime()+lifetime*24*3600*1000l));
    }

    @Override
    public void deleteLinkInfoByID(Integer id) {
        linkInfoMapper.deleteLinkInfoByInfoid(id);
    }


}
